package com.pay.ioopos;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.util.Log;

import androidx.annotation.NonNull;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SubScreenBackgroudLoader {
    private static final String TAG = SubScreenBackgroudLoader.class.getSimpleName();
    private Bitmap defBgBitmap;
    private boolean subScreenBackbgroudLoaded = false;
    private Bitmap payInitBitmap;
    private Bitmap payingBitmap;
    private Bitmap paySuccessBitmap;
    private Bitmap payFailBitmap;
    private Bitmap payUnknownBitmap;
    private Bitmap payCancelBitmap;

    private static SubScreenBackgroudLoader loader = new SubScreenBackgroudLoader();

    private SubScreenBackgroudLoader() {

    }

    public static SubScreenBackgroudLoader getInstance() {
        return loader;
    }

    public void load(Activity activity) {
        if (subScreenBackbgroudLoaded) {
            return;
        }

        loadDef(activity);
        //loadRemote(activity);

    }

    private void loadDef(Activity activity) {
        if (null == defBgBitmap) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inMutable = true;
            options.inScaled = true;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            defBgBitmap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.sub_screen_backgroud, options);
        }
        Bitmap  bitmap = Bitmap.createScaledBitmap(defBgBitmap, 480, 320, true);
        payInitBitmap = bitmap;
        payingBitmap = bitmap;
        paySuccessBitmap = bitmap;
        payFailBitmap = bitmap;
        payUnknownBitmap = bitmap;
        subScreenBackbgroudLoaded = true;

    }

    private void loadRemote(Activity activity) {
        String dir = activity.getFilesDir().getAbsolutePath() + File.separator;
        try {
            payInitBitmap = BitmapFactory.decodeFile(dir + "payInit_bg.png");
            payingBitmap = BitmapFactory.decodeFile(dir + "paying_bg.png");
            paySuccessBitmap = BitmapFactory.decodeFile(dir + "paySuccess_bg.png");
            payFailBitmap = BitmapFactory.decodeFile(dir + "payFail_bg.png");
            payUnknownBitmap = BitmapFactory.decodeFile(dir + "payUnknown_bg.png");
        } catch (Exception e) {
            Log.e(TAG, "load: ", e);
        }
        ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        connectivityManager.requestNetwork(new NetworkRequest.Builder().build(), new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull Network network) {
                super.onAvailable(network);
                startLoadSubScreenBackgroud(activity);
            }

            @Override
            public void onLost(@NonNull Network network) {
                super.onLost(network);
            }
        });
    }

    public Bitmap getPayInitBitmap() {
        return payInitBitmap;
    }

    public Bitmap getPayingBitmap() {
        return payingBitmap;
    }

    public Bitmap getPayCancelBitmap() {
        return payingBitmap;
    }

    public Bitmap getPaySuccessBitmap() {
        return paySuccessBitmap;
    }

    public Bitmap getPayFailBitmap() {
        return payFailBitmap;
    }

    public Bitmap getPayUnknownBitmap() {
        return payUnknownBitmap;
    }


    private void startLoadSubScreenBackgroud(Activity activity) {
        if (subScreenBackbgroudLoaded) {
            return;
        }
        Thread thread = new Thread(() -> {
            try {
                DataStore store = DataFactory.getDataStore();
                String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                String sn = Utils.sn();
                String key = store.getTransKey();
                String sign = Utils.sha256(sn + timestamp + key);
                JSONObject json = new JSONObject();
                json.put("version", "v2");
                json.put("deviceSn", sn);
                json.put("brand", "ioopos");
                json.put("timestamp", timestamp);
                json.put("sign", sign);
                String jsonString = json.toString();
                jsonString = HttpUtil.post("https://app.campusplus.com/dzxyk-hd/devicebg/index.php", jsonString);
                json = new JSONObject(jsonString);
                String bgInit = json.getString("bgInit");
                String bgPaying = json.getString("bgPaying");
                String bgSuccess = json.getString("bgSuccess");
                String bgFail = json.getString("bgFail");
                String bgUnknown = json.getString("bgUnknow");

                payInitBitmap = save(activity, bgInit, "payInit_bg.png");
                payingBitmap = save(activity, bgPaying, "paying_bg.png");
                paySuccessBitmap = save(activity, bgSuccess, "paySuccess_bg.png");
                payFailBitmap = save(activity, bgFail, "payFail_bg.png");
                payUnknownBitmap = save(activity, bgUnknown, "payUnknown_bg.png");

            } catch(Exception e) {
                Log.e(TAG, "startLoadSubScreenBackgroud: ", e);
            }
        });
        thread.start();
    }

    private Bitmap save(Activity activity, String url, String fileName) {
        File file = new File(activity.getFilesDir(), fileName);
        file.setWritable(true);
        byte[] bytes = new byte[1024];
        int len;
        try (InputStream is = new URL(url).openStream(); FileOutputStream fos = new FileOutputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            while ((len = is.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
                bos.write(bytes, 0, len);
            }
            subScreenBackbgroudLoaded = true;
            return BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size());
        } catch (Exception e) {
            try (InputStream is = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                while ((len = is.read(bytes)) != -1) {
                    bos.write(bytes, 0, len);
                }
                return BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size());
            } catch (IOException e1) {
                Log.e(TAG, "save: ", e1);
            }
        }
        return null;
    }

}
